package com.bestom.hardwaretest.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import com.bestom.hardwaretest.File.FilesManager;
import com.bestom.hardwaretest.R;
import com.bestom.hardwaretest.util.ToastUtil;
import com.suke.widget.SwitchButton;

import pl.droidsonroids.gif.GifImageView;

public class MainActivity extends BaseActivity {

    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        initView();

    }

    @Override
    protected void onResume() {

        initData();
        startReadRadar();
        super.onResume();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        if (item.getItemId() == R.id.set)
            startActivity(new Intent(MainActivity.this, SettingActivity.class));
        else if(item.getItemId()==android.R.id.home){
            new AlertDialog.Builder(this)
                    .setTitle("关闭应用")
                    .setMessage("确定要退出此应用吗？")
                    .setPositiveButton("确定", (dialog, which) -> finish())
                    .setNegativeButton("取消", null)
                    .show();
        }
        return super.onOptionsItemSelected(item);
    }

    private GifImageView radar;

    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle(getString(R.string.app_name));
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        radar = findViewById(R.id.radar);
        SwitchButton led = findViewById(R.id.led);
        SwitchButton ir = findViewById(R.id.ir);
        SwitchButton relay = findViewById(R.id.relay);
        SwitchButton buzzer = findViewById(R.id.buzzer);
        led.setOnCheckedChangeListener((view, isChecked) -> {
            if (!mFilesManager.writeLed(isChecked ? "10000" : "0")) ToastUtil.toast("LED GPIO节点错误，请检查！");
        });
        ir.setOnCheckedChangeListener((view, isChecked) -> {
            if (!mFilesManager.writeRedLed(isChecked ? "1" : "0")) ToastUtil.toast("IR GPIO节点错误，请检查！");
        });
        relay.setOnCheckedChangeListener((view, isChecked) -> {
            if (!mFilesManager.writeRelay(isChecked ? "1" : "0")) ToastUtil.toast("继电器GPIO节点错误，请检查！");
        });
        buzzer.setOnCheckedChangeListener((view, isChecked) -> {
            if (!mFilesManager.writeBuzzer(isChecked ? "1" : "0")) ToastUtil.toast("蜂鸣器GPIO节点错误，请检查！");
        });
        findViewById(R.id.ble).setOnClickListener(view -> {
            Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
            intent.putExtra(":settings:show_fragment_as_subsetting", true);
            startActivity(intent);
//            startActivity(new Intent(MainActivity.this, BleActivity.class));
        });
        findViewById(R.id.btn_485).setOnClickListener(view -> startActivity(new Intent(MainActivity.this, SerialportActivity.class)));
        findViewById(R.id.wifi).setOnClickListener(view -> {
            Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
            intent.putExtra(":settings:show_fragment_as_subsetting", true);
            startActivity(intent);
//            startActivity(new Intent(MainActivity.this, WiFiActivity.class));
        });
        findViewById(R.id.camera).setOnClickListener(view -> {
            //6.0+调用相机权限
            if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 61);
            else startActivity(new Intent(MainActivity.this, CameraActivity.class));
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        int granted = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]);
        if (PackageManager.PERMISSION_GRANTED != granted) ToastUtil.toast("未能获取到摄像头权限，无法使用此功能！");
        else startActivity(new Intent(MainActivity.this, CameraActivity.class));
    }
    private FilesManager mFilesManager;

    @SuppressLint("ResourceType")
    private void initData() {
        if (mFilesManager != null) mFilesManager = null;
        mFilesManager = new FilesManager();
        mFilesManager.writeRedLed("0");
    }

    private void startReadRadar(){
        if (mHandler == null) mHandler = new Handler();
        mHandler.postDelayed(mRunnable,1000);
    }
    private Handler mHandler;
    private static String oldRadarData;
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            String radarData = "1";
            String newRadarData = mFilesManager.readRadar();
            if (newRadarData == null) {
                ToastUtil.toast("雷达GPIO节点错误，请检查！");
                mHandler.postDelayed(this,6000);
            }else {
                if (newRadarData.equals(radarData)){
                    if (!newRadarData.equals(oldRadarData)){
                        radar.setImageResource(R.drawable.yes_radar);
                        oldRadarData = newRadarData;
                    }
                }else {
                    if (!newRadarData.equals(oldRadarData)){
                        radar.setImageResource(R.drawable.no_radar);
                        oldRadarData = newRadarData;
                    }
                }
                mHandler.postDelayed(this,1000);
            }
        }
    };

    @Override
    protected void onStop() {
        if (mHandler != null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacks(mRunnable);
            mRunnable = null;
            mHandler = null;
        }
    }
}